<?php

namespace app\controller\api;

use app\BaseController;
use think\facade\Cache;
use think\helper\Str;
use think\response\Json;

class User extends BaseController
{
    public function detail(): Json
    {
        return $this->handle(function () {
            if(empty($this->request->user)) throw new \Exception('请登录！');
            return $this->request->user;
        });
    }

    public function get_sms_code(): Json
    {
        return $this->handle(function () {
//            Cache::clear();
            $param = request()->param();
            $phone = $param['mobile'];
            $code = Str::random(4, 1);
            $timer = Cache::get("user_sms_code_$phone", 0);
            if ($timer > 5) throw new \Exception('你已经请求太多次验证码，请稍后再次获取！');
            $nowCode = Cache::get("user_sms_code_first_$phone");
            if ($nowCode) throw new \Exception('请勿重复发送验证码！');
            //获取短信验证码
            $user = $this->app->make(\app\model\User::class)->where('mobile', $phone)->where('state', 1)->where('is_del', 1)->find();
            if (empty($user)) throw new \Exception('登录账号异常，请联系管理员！');
            $ip = $this->request->ip();
            if ($ip == "127.0.0.1") {
                $code = 1234;
            } else {
                $send = sendSms("191585", $phone, compact("code"));
                if (!$send) throw new \Exception('发送验证码失败！');
            }
            Cache::set("user_sms_code_first_$phone", $timer + 1, 60);
            Cache::set("user_sms_code_$phone", $code, 60 * 5);
            return [];
        });
    }

    public function login(): Json
    {
        return $this->handle(function () {
            $param = request()->param();
            $phone = $param['mobile'];
            $code = $param['code'];
            //获取短信验证码
            $user = $this->app->make(\app\model\User::class)->where('mobile', $phone)->where('state', 1)->where('is_del', 1)->find();
            if (empty($user)) throw new \Exception('登录账号异常，请联系管理员！');
            $sendCode = Cache::get("user_sms_code_$phone");
            if (empty($sendCode)) throw new \Exception('验证码已过期！');
            if ($sendCode != $code) throw new \Exception('验证码错误！');
            Cache::delete("user_sms_code_$phone");
            Cache::delete("user_sms_code_first_$phone");
            $token = $this->token();
            Cache::set("api_$token", ['id' => $user->id, 'verify_time' => strtotime('+7 day')], 60 * 60 * 24 * 7);
            return ["token" => $token];
        });
    }

    private function token()
    {
        $token = Str::random(32);
        if (Cache::has("api_$token")) $this->token();
        return $token;
    }
}
